package hashbuck;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yi
 * Date: 2024-08-01
 * Time: 16:29
 */
public class HashBuck2<K,V> {
    static class Node<K,V> {
        public K key;
        public V value;
        public Node<K,V> next;

        public Node(K key,V val) {
            this.key = key;
            this.value = val;
        }
    }

    public Node<K,V>[] elem;
    public int usedSize;
    //初始化构造方法
    public HashBuck2() {
        this.elem = (Node<K,V>[])new Node[10];
    }

    public void put(K key,V val) {
        Node node = new Node(key,val);
        int hash = key.hashCode();
        int index = hash % this.elem.length;
        Node cur = this.elem[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        node.next = this.elem[index];
        this.elem[index] = node;
        this.usedSize++;

        if(loadFactor() >= 0.75) {
            //调用扩容函数
            resize();
        }
    }

    private double loadFactor() {
        return this.usedSize*1.0 / this.elem.length;
    }

    private void resize() {
        Node[] tmpArr = new Node[this.elem.length*2];
        for (int i = 0; i < this.elem.length; i++) {
            Node cur = this.elem[i];
            while(cur != null) {
                //记录cur.next的位置
                Node curNext = cur.next;
                int newIndex = cur.key.hashCode() / tmpArr.length;
                //头插法
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }

        this.elem = tmpArr;
    }

    public V get(K key) {
        int index = key.hashCode() % this.elem.length;
        Node cur = this.elem[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                return (V) cur.value;
            }
            cur = cur.next;
        }
        return null;
    }

}
